package org.totoro.concurrent.juc.sync;

import java.util.concurrent.Semaphore;

/**
 * 信号量
 *
 * @author YHL
 * @version V1.0
 * @Description:
 * @date 2018-12-27
 */
public class SemaphoreTest {

    /**
     *  类似 于 限流
     *
     * @param args
     */
    public static void main(String[] args) throws InterruptedException {


        Integer count = 10;

        Semaphore semaphore = new Semaphore(2);


        for (Integer i = 0; i < count; i++) {

            new Thread(() -> {
                try {
                    Thread thread = Thread.currentThread();

                    semaphore.acquire();
                    System.out.println(thread.getName() + "占领一个座位");

                    double random = Math.random();
                    Thread.sleep(Double.valueOf(String.valueOf(random * 5000)).longValue());

                    semaphore.release();
                    System.out.println(thread.getName() + "释放一个座位 ");

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }).start();


        }


    }
}
